<?php
class Rdf_model_product extends Model {
    private $table_node = 'n_node';
    private $table_product = 'product';
    private $table_page = 'page';
    private $table_mapping = 'n_mapping';
    
    
    public function get_product_ranges($offset = 0, $limit = 5) {
        $table_page = $this->table_page;
        $table_node = $this->table_node;
        $offset = (int) $offset;
        $limit = (int) $limit;
        
        $sql = "SELECT `n`.`id`, `n`.`caption`, `n`.`url_segment`, `n`.`thumbnail` FROM `{$table_node}` `n` " .
            "INNER JOIN `{$table_page}` `p` ON `n`.`id`=`p`.`node_id` WHERE `p`.`template`='product_range' " . 
            "ORDER BY `n`.`rank` DESC, `n`.`child_hit` DESC, `n`.`next_hit` DESC, `n`.`changed` DESC " .
            "LIMIT $offset,$limit";
        
        return $this->db->rows($sql);
    }
    
    
    public function get_product_galleries() {
        $table_page = $this->table_page;
        $table_node = $this->table_node;
        
        $sql = "SELECT `n`.`id`, `n`.`caption`, `n`.`url_segment`, `n`.`thumbnail` FROM `{$table_node}` `n` " .
            "INNER JOIN `{$table_page}` `p` ON `n`.`id`=`p`.`node_id` WHERE `p`.`template`='product_gallery' ORDER BY `n`.`rank` DESC, `n`.`child_hit` DESC, `n`.`next_hit` DESC, `n`.`changed` DESC ";
        
        return $this->db->rows($sql);
    }
    
    
    public function get_products_by_gallery_id($gallery_id, $offset = 0, $limit = 8) {
        $offset = (int) $offset;
        $limit = (int) $limit;
        $gallery_id = (int) $gallery_id;
        if ($gallery_id <= 0) tos_die();
        
        return $this->db->select_rows(
            $this->table_node,
            array('id', 'caption', 'url_segment','caption', 'thumbnail'),
            array('parent_id' => $gallery_id),
            array(),
            array('rank' => 'DESC', 'child_hit' => 'DESC', 'next_hit' => 'DESC', 'changed' => 'DESC'),
            $offset, $limit
        );
    }
    
    
    public function get_count_by_gallery_id($gallery_id) {
        $parent_id = (int) $gallery_id;
        $sql = "SELECT count(*) count FROM `{$this->table_node}` WHERE `parent_id`='{$parent_id}'";
        $row = $this->db->row($sql);
        if ($row) {
            return (int) $row['count'];
        }
        return 0;
    }
    
    public function get_products_by_range_id($range_id) {
        $range_id = (int) $range_id;
        
        $sql = "SELECT `n`.`id`, `n`.`thumbnail`, `n`.`caption`, `n`.`url_segment` FROM `{$this->table_node}` `n`" .
            "INNER JOIN `{$this->table_mapping}` `m` ON `m`.`next_id`=`n`.`id` " . 
            "WHERE `m`.`prev_id`={$range_id} ORDER BY `n`.`rank` DESC, `n`.`child_hit` DESC, `n`.`next_hit` DESC , `n`.`changed` DESC";
        return $this->db->rows($sql);
    }
}
?>